<template>
  <div class="login-container">
    <div class="background-decoration">
      <div class="floating-shape shape-1"></div>
      <div class="floating-shape shape-2"></div>
      <div class="floating-shape shape-3"></div>
      <div class="floating-shape shape-4"></div>
      <div class="floating-shape shape-5"></div>
    </div>
    
    <div class="login-content">
      <div class="login-box">
        <div class="login-header">
          <div class="logo-section">
            <div class="logo-icon">
              <el-icon size="40"><School /></el-icon>
            </div>
            <h2 class="system-title">学生管理系统</h2>
          </div>
          <p class="welcome-text">欢迎登录</p>
        </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        autocomplete="off"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名/学号/工号"
            size="large"
            prefix-icon="User"
            clearable
            autocomplete="new-password"
            readonly
            @focus="handleUsernameFocus"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            clearable
            autocomplete="new-password"
          />
        </el-form-item>

        <div style="color:#909399;font-size:12px;margin:0 0 10px 0;">提示：请输入用户名、学号或工号进行登录</div>
        
        <el-form-item>
          <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleLogin"
            style="width: 100%"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p>还没有账号？ <a href="#" @click="showRegister">立即注册</a></p>
      </div>
      </div>
    </div>
    
    <!-- 注册对话框 -->
    <el-dialog
      v-model="registerVisible"
      title="用户注册"
      width="400px"
      :close-on-click-modal="false"
      @open="onRegisterOpen"
    >
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="80px"
        autocomplete="off"
      >
        <el-form-item :label="getRegisterFieldLabel()" prop="username">
          <el-input 
            v-model="registerForm.username" 
            :placeholder="getRegisterFieldPlaceholder()" 
            autocomplete="off" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="registerForm.role">
            <el-radio label="student">学生</el-radio>
            <el-radio label="teacher">教师</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="registerVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRegister" :loading="registerLoading">
            {{ registerLoading ? '注册中...' : '注册' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { School } from '@element-plus/icons-vue'
import { md5 } from '../utils/md5'
import loginAPI from '../api/login'

export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    const loginFormRef = ref()
    const registerFormRef = ref()
    const loading = ref(false)
    const registerLoading = ref(false)
    const registerVisible = ref(false)

    const loginForm = reactive({
      username: '',
      password: '',
      remember: false
    })

    const registerForm = reactive({
      username: '',
      password: '',
      confirmPassword: '',
      role: 'student'
    })

    const loginRules = {
      username: [
        { required: true, message: '请输入用户名/学号/工号', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ]
    }

    const registerRules = {
      username: [
        { 
          required: true, 
          validator: (rule, value, callback) => {
            const role = registerForm.role
            if (!value) {
              if (role === 'student') callback(new Error('请输入学号'))
              else if (role === 'teacher') callback(new Error('请输入工号'))
              else callback(new Error('请输入用户名'))
            } else {
              if (role === 'admin' && (value.length < 3 || value.length > 20)) {
                callback(new Error('用户名长度在 3 到 20 个字符'))
              } else {
                callback()
              }
            }
          },
          trigger: ['blur', 'change']
        }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== registerForm.password) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ]
    }

    const handleLogin = async () => {
      if (!loginFormRef.value) return
      
      await loginFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            const response = await loginAPI.login({
              username: loginForm.username,
              password: md5(loginForm.password)
            })
            
            if (response.data.code === 1) {
              const userData = response.data.data;
              console.log('登录成功，用户数据:', userData);
              
              // 保存登录状态
              localStorage.setItem('isLoggedIn', 'true');
              
              // 保存用户标识信息
              localStorage.setItem('userId', userData.id);
              localStorage.setItem('username', userData.username);
              localStorage.setItem('name', userData.username); // 用于显示的名字
              
              // 保存角色信息
              const role = userData.role || 'student';
              localStorage.setItem('role', role);
              
              // 保存学号/工号
              const stuId = userData.stuteaid || userData.username;
              localStorage.setItem('stuId', stuId);
              
              ElMessage.success('登录成功')
              // 根据角色跳转
              if (role === 'teacher') {
                router.push('/dashboard/teacher')
              } else if (role === 'student') {
                router.push('/dashboard/student')
              } else {
                router.push('/dashboard/home')
              }
            } else {
              ElMessage.error(response.data.message || '登录失败')
            }
          } catch (error) {
            ElMessage.error('登录失败，请检查用户名和密码')
            console.error('登录错误:', error)
          } finally {
            loading.value = false
          }
        }
      })
    }

    const resetRegisterForm = () => {
      if (registerFormRef.value) {
        registerFormRef.value.clearValidate()
      }
      Object.assign(registerForm, {
        username: '',
        password: '',
        confirmPassword: '',
        role: 'student'
      })
    }

    const showRegister = () => {
      resetRegisterForm()
      registerVisible.value = true
    }

    const getRegisterFieldLabel = () => {
      switch (registerForm.role) {
        case 'student': return '学号'
        case 'teacher': return '教工号'
        case 'admin': return '用户名'
        default: return '账号'
      }
    }

    const getRegisterFieldPlaceholder = () => {
      switch (registerForm.role) {
        case 'student': return '请输入学号'
        case 'teacher': return '请输入教工号'
        case 'admin': return '请输入用户名'
        default: return '请输入账号'
      }
    }

    const handleUsernameFocus = (event) => {
      // 移除只读属性，允许用户输入
      event.target.removeAttribute('readonly')
    }

    const onRegisterOpen = () => {
      resetRegisterForm()
    }

    const handleRegister = async () => {
      if (!registerFormRef.value) return
      
      await registerFormRef.value.validate(async (valid) => {
        if (valid) {
          registerLoading.value = true
          try {
            const requestData = {
              username: registerForm.username,
              password: md5(registerForm.password),
              role: registerForm.role,
              stuteaid: registerForm.role !== 'admin' ? registerForm.username : null
            }
            console.log('注册请求数据:', requestData)
            const response = await loginAPI.register(requestData)
            
            if (response.data.code === 1) {
              ElMessage.success('注册成功，请登录')
              registerVisible.value = false
              resetRegisterForm()
            } else {
              ElMessage.error(response.data.message || '注册失败')
            }
          } catch (error) {
            const errorMsg = error.response?.data?.message || '注册失败，请重试'
            ElMessage.error(errorMsg)
            console.error('注册错误:', error)
          } finally {
            registerLoading.value = false
          }
        }
      })
    }

    // 检查是否已登录
    onMounted(() => {
      const isLoggedIn = localStorage.getItem('isLoggedIn')
      if (isLoggedIn === 'true') {
        const role = localStorage.getItem('role') || 'student'
        if (role === 'admin') {
          router.push('/dashboard/home')
        } else if (role === 'student') {
          router.push('/dashboard/student')
        } else if (role === 'teacher') {
          router.push('/dashboard/teacher')
        } else {
          router.push('/dashboard/home')
        }
      }
      
      // 确保表单为空
      loginForm.username = ''
      loginForm.password = ''
      loginForm.remember = false
    })

    return {
      loginFormRef,
      registerFormRef,
      loading,
      registerLoading,
      registerVisible,
      loginForm,
      registerForm,
      loginRules,
      registerRules,
      handleLogin,
      showRegister,
      handleRegister,
      onRegisterOpen,
      getRegisterFieldLabel,
      getRegisterFieldPlaceholder,
      handleUsernameFocus,
      School
    }
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 8s ease-in-out infinite;
}

.shape-1 {
  width: 120px;
  height: 120px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
  background: rgba(255, 255, 255, 0.08);
}

.shape-2 {
  width: 80px;
  height: 80px;
  top: 20%;
  right: 15%;
  animation-delay: 2s;
  background: rgba(255, 193, 7, 0.15);
}

.shape-3 {
  width: 60px;
  height: 60px;
  bottom: 30%;
  left: 20%;
  animation-delay: 4s;
  background: rgba(76, 175, 80, 0.12);
}

.shape-4 {
  width: 100px;
  height: 100px;
  bottom: 15%;
  right: 25%;
  animation-delay: 1s;
  background: rgba(233, 30, 99, 0.1);
}

.shape-5 {
  width: 40px;
  height: 40px;
  top: 60%;
  left: 80%;
  animation-delay: 3s;
  background: rgba(255, 255, 255, 0.12);
}

@keyframes float {
  0%, 100% { 
    transform: translateY(0px) rotate(0deg);
    opacity: 0.6;
  }
  25% { 
    transform: translateY(-20px) rotate(90deg);
    opacity: 0.8;
  }
  50% { 
    transform: translateY(-40px) rotate(180deg);
    opacity: 1;
  }
  75% { 
    transform: translateY(-20px) rotate(270deg);
    opacity: 0.7;
  }
}

/* 登录内容 */
.login-content {
  position: relative;
  z-index: 2;
}

.login-box {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
  padding: 50px 40px;
  width: 420px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: slideUp 0.8s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 登录头部 */
.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  animation: fadeIn 1s ease-out 0.3s both;
}

.logo-icon {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #74b9ff 0%, #00cec9 100%);
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 16px;
  box-shadow: 0 8px 20px rgba(116, 185, 255, 0.3);
}

.system-title {
  color: #2d3748;
  margin: 0;
  font-size: 28px;
  font-weight: 800;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.welcome-text {
  color: #718096;
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  animation: fadeIn 1s ease-out 0.5s both;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

/* 表单样式 */
.login-form {
  margin-bottom: 30px;
  animation: fadeIn 1s ease-out 0.7s both;
}

.login-form .el-form-item {
  margin-bottom: 25px;
}

.login-form .el-input {
  border-radius: 12px;
  overflow: hidden;
}

.login-form .el-input__wrapper {
  background: rgba(248, 250, 252, 0.8);
  border: 2px solid rgba(226, 232, 240, 0.5);
  border-radius: 12px;
  padding: 12px 16px;
  transition: all 0.3s ease;
  box-shadow: none;
}

.login-form .el-input__wrapper:hover {
  border-color: rgba(116, 185, 255, 0.3);
  background: rgba(255, 255, 255, 0.9);
}

.login-form .el-input.is-focus .el-input__wrapper {
  border-color: #74b9ff;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 0 0 3px rgba(116, 185, 255, 0.1);
}

.login-form .el-button--primary {
  background: linear-gradient(135deg, #74b9ff 0%, #00cec9 100%);
  border: none;
  border-radius: 12px;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  box-shadow: 0 8px 20px rgba(116, 185, 255, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.login-form .el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 30px rgba(116, 185, 255, 0.4);
}

.login-form .el-checkbox {
  color: #4a5568;
  font-weight: 500;
}

/* 登录底部 */
.login-footer {
  text-align: center;
  color: #718096;
  font-size: 14px;
  animation: fadeIn 1s ease-out 0.9s both;
}

.login-footer a {
  color: #74b9ff;
  text-decoration: none;
  font-weight: 600;
  transition: color 0.3s ease;
}

.login-footer a:hover {
  color: #667eea;
  text-decoration: underline;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-box {
    width: 90%;
    max-width: 380px;
    padding: 40px 30px;
    margin: 20px;
  }
  
  .logo-section {
    flex-direction: column;
  }
  
  .logo-icon {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .system-title {
    font-size: 24px;
  }
  
  .floating-shape {
    opacity: 0.3;
  }
}

@media (max-width: 480px) {
  .login-box {
    padding: 30px 20px;
  }
  
  .system-title {
    font-size: 22px;
  }
  
  .welcome-text {
    font-size: 14px;
  }
}
</style>

<style scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 8s ease-in-out infinite;
}

.shape-1 {
  width: 120px;
  height: 120px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
  background: rgba(255, 255, 255, 0.08);
}

.shape-2 {
  width: 80px;
  height: 80px;
  top: 20%;
  right: 15%;
  animation-delay: 2s;
  background: rgba(255, 193, 7, 0.15);
}

.shape-3 {
  width: 60px;
  height: 60px;
  bottom: 30%;
  left: 20%;
  animation-delay: 4s;
  background: rgba(76, 175, 80, 0.12);
}

.shape-4 {
  width: 100px;
  height: 100px;
  bottom: 15%;
  right: 25%;
  animation-delay: 1s;
  background: rgba(233, 30, 99, 0.1);
}

.shape-5 {
  width: 40px;
  height: 40px;
  top: 60%;
  left: 80%;
  animation-delay: 3s;
  background: rgba(255, 255, 255, 0.12);
}

@keyframes float {
  0%, 100% { 
    transform: translateY(0px) rotate(0deg);
    opacity: 0.6;
  }
  25% { 
    transform: translateY(-20px) rotate(90deg);
    opacity: 0.8;
  }
  50% { 
    transform: translateY(-40px) rotate(180deg);
    opacity: 1;
  }
  75% { 
    transform: translateY(-20px) rotate(270deg);
    opacity: 0.7;
  }
}

/* 登录内容 */
.login-content {
  position: relative;
  z-index: 2;
}

.login-box {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
  padding: 50px 40px;
  width: 420px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: slideUp 0.8s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 登录头部 */
.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  animation: fadeIn 1s ease-out 0.3s both;
}

.logo-icon {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #74b9ff 0%, #00cec9 100%);
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 16px;
  box-shadow: 0 8px 20px rgba(116, 185, 255, 0.3);
}

.system-title {
  color: #2d3748;
  margin: 0;
  font-size: 28px;
  font-weight: 800;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.welcome-text {
  color: #718096;
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  animation: fadeIn 1s ease-out 0.5s both;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

/* 表单样式 */
.login-form {
  margin-bottom: 30px;
  animation: fadeIn 1s ease-out 0.7s both;
}

.login-form .el-form-item {
  margin-bottom: 25px;
}

.login-form .el-input {
  border-radius: 12px;
  overflow: hidden;
}

.login-form .el-input__wrapper {
  background: rgba(248, 250, 252, 0.8);
  border: 2px solid rgba(226, 232, 240, 0.5);
  border-radius: 12px;
  padding: 12px 16px;
  transition: all 0.3s ease;
  box-shadow: none;
}

.login-form .el-input__wrapper:hover {
  border-color: rgba(116, 185, 255, 0.3);
  background: rgba(255, 255, 255, 0.9);
}

.login-form .el-input.is-focus .el-input__wrapper {
  border-color: #74b9ff;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 0 0 3px rgba(116, 185, 255, 0.1);
}

.login-form .el-button--primary {
  background: linear-gradient(135deg, #74b9ff 0%, #00cec9 100%);
  border: none;
  border-radius: 12px;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  box-shadow: 0 8px 20px rgba(116, 185, 255, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.login-form .el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 30px rgba(116, 185, 255, 0.4);
}

.login-form .el-checkbox {
  color: #4a5568;
  font-weight: 500;
}

/* 登录底部 */
.login-footer {
  text-align: center;
  color: #718096;
  font-size: 14px;
  animation: fadeIn 1s ease-out 0.9s both;
}

.login-footer a {
  color: #74b9ff;
  text-decoration: none;
  font-weight: 600;
  transition: color 0.3s ease;
}

.login-footer a:hover {
  color: #667eea;
  text-decoration: underline;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-box {
    width: 90%;
    max-width: 380px;
    padding: 40px 30px;
    margin: 20px;
  }
  
  .logo-section {
    flex-direction: column;
  }
  
  .logo-icon {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .system-title {
    font-size: 24px;
  }
  
  .floating-shape {
    opacity: 0.3;
  }
}

@media (max-width: 480px) {
  .login-box {
    padding: 30px 20px;
  }
  
  .system-title {
    font-size: 22px;
  }
  
  .welcome-text {
    font-size: 14px;
  }
}
</style>
